import type { Directive, DirectiveBinding } from 'vue';

interface ScrollOptions {
  throttle?: number;  // 节流时间（毫秒）
  passive?: boolean;  // 是否使用被动事件监听
  horizontal?: boolean; // 是否水平滚动
  hideTimeout?: number; // 滚动停止后隐藏滚动条的延迟时间
}

/**
 * 优化滚动体验的自定义指令
 * 
 * 使用方法:
 * v-better-scroll - 基本用法，自动优化滚动
 * v-better-scroll="{ throttle: 16, passive: true }" - 配置节流和被动监听
 * v-better-scroll="{ horizontal: true }" - 启用水平滚动优化
 * v-better-scroll="{ hideTimeout: 1000 }" - 设置滚动停止后1秒隐藏滚动条
 */
export const betterScroll: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const options: ScrollOptions = binding.value || {};

    // 设置默认值
    const throttle = options.throttle || 16; // 约60fps
    const passive = options.passive !== false;
    const horizontal = options.horizontal || false;
    const hideTimeout = options.hideTimeout || 500;

    // 添加自定义滚动类
    el.classList.add('custom-scroll');

    // 滚动中标记
    let isScrolling = false;

    // 滚动延时器
    let scrollTimer: number | null = null;

    // 节流函数
    let lastScrollTime = 0;

    // 滚动方向检测
    let lastScrollPos = horizontal ? el.scrollLeft : el.scrollTop;
    let scrollDirection = '';

    // 滚动处理函数
    const handleScroll = () => {
      const now = Date.now();

      // 节流处理
      if (now - lastScrollTime < throttle) return;
      lastScrollTime = now;

      // 检测滚动方向
      const currentPos = horizontal ? el.scrollLeft : el.scrollTop;
      scrollDirection = currentPos > lastScrollPos ? 'down' : 'up';
      lastScrollPos = currentPos;

      // 标记正在滚动
      if (!isScrolling) {
        isScrolling = true;
        el.classList.add('is-scrolling');
        el.setAttribute('data-scroll-direction', scrollDirection);
      }

      // 重置隐藏计时器
      if (scrollTimer) {
        window.clearTimeout(scrollTimer);
        scrollTimer = null;
      }

      // 设置隐藏计时器
      scrollTimer = window.setTimeout(() => {
        isScrolling = false;
        el.classList.remove('is-scrolling');
        el.removeAttribute('data-scroll-direction');
      }, hideTimeout);
    };

    // 添加滚动事件监听
    el.addEventListener('scroll', handleScroll, { passive });

    // 存储清理函数
    el._betterScrollCleanup = () => {
      el.removeEventListener('scroll', handleScroll);
      if (scrollTimer) {
        window.clearTimeout(scrollTimer);
        scrollTimer = null;
      }
    };
  },

  beforeUnmount(el: HTMLElement) {
    // 清理事件监听
    if (el._betterScrollCleanup) {
      el._betterScrollCleanup();
      delete el._betterScrollCleanup;
    }
  }
}; 